#!/bin/sh
#
# Perform necessary datadog-iot-agent removal steps after package is uninstalled.
#
# .deb: STEP 3 of 5
# .rpm: STEP 5 of 6

KNOWN_DISTRIBUTION="(Debian|Ubuntu|RedHat|CentOS|openSUSE|Amazon|Arista|SUSE|Rocky|AlmaLinux)"
DISTRIBUTION=$(lsb_release -d 2>/dev/null | grep -Eo $KNOWN_DISTRIBUTION  || grep -Eo $KNOWN_DISTRIBUTION /etc/issue 2>/dev/null || grep -Eo $KNOWN_DISTRIBUTION /etc/Eos-release 2>/dev/null || grep -m1 -Eo $KNOWN_DISTRIBUTION /etc/os-release 2>/dev/null || uname -s)

INSTALL_DIR=/opt/datadog-agent
LOG_DIR=/var/log/datadog
CONFIG_DIR=/etc/datadog-agent

# Remove the symlink to the binary.
rm -f "/usr/bin/datadog-agent"

if [ -f "/etc/debian_version" ] || [ "$DISTRIBUTION" = "Debian" ] || [ "$DISTRIBUTION" = "Ubuntu" ]; then
    set -e

    case "$1" in
        purge)
            echo "Deleting dd-agent user"
            deluser dd-agent --quiet
            echo "Deleting dd-agent group"
            (getent group dd-agent >/dev/null && delgroup dd-agent --quiet) || true
            echo "Force-deleting $INSTALL_DIR"
            rm -rf $INSTALL_DIR
            rm -rf $LOG_DIR
            rm -rf $CONFIG_DIR
        ;;
        *)
        ;;
    esac
elif [ -f "/etc/redhat-release" ] || [ -f "/etc/system-release" ] || [ -f "/etc/SuSE-release" ] || [ "$DISTRIBUTION" = "RedHat" ] || [ "$DISTRIBUTION" = "CentOS" ] || [ "$DISTRIBUTION" = "openSUSE" ] || [ "$DISTRIBUTION" = "Amazon" ] || [ "$DISTRIBUTION" = "SUSE" ] || [ "$DISTRIBUTION" = "Arista" ] || [ "$DISTRIBUTION" = "Rocky" ] || [ "$DISTRIBUTION" = "AlmaLinux" ]; then
    case "$*" in
        0)
            # We're uninstalling.
            # We don't delete the dd-agent user/group (see https://fedoraproject.org/wiki/Packaging:UsersAndGroups#Allocation_Strategies)
        ;;
        1)
            # We're upgrading.
        ;;
        *)
        ;;
    esac
else
    echo "[ FAILED ]\tYour system is currently not supported by this script.";
fi

exit 0
